package com.china.zhuoyue.ui.activity.login

import android.view.View
import android.view.animation.AnimationUtils
import com.china.zhuoyue.BuildConfig
import com.china.zhuoyue.R
import com.china.zhuoyue.api.login.launchUILogin
import com.china.zhuoyue.databinding.ActivityLoginBinding
import com.china.zhuoyue.ui.activity.main.MainActivity
import com.china.zhuoyue.ui.api.ApiObserver
import com.china.zhuoyue.ui.base.BaseActivity
import com.china.zhuoyue.ui.cache.UserCache
import com.china.zhuoyue.ui.ext.startActivityExt
import com.china.zhuoyue.ui.ext.toastMessageLong
import com.china.zhuoyue.ui.ext.value
import com.china.zhuoyue.ui.utils.Utils
import com.china.zhuoyue.ui.utils.variableView
import com.tencent.smtt.utils.Md5Utils

class LoginActivity : BaseActivity<ActivityLoginBinding>() {
    override fun initView() {
        loadView {
            bindViewClick(
                buttonLogin,
                textLoginForgetPassword,
                textLoginRegister,
            )

            if (BuildConfig.DEBUG) {
                etPhone.setText("18888888888")
                etPassword.setText("123456")
            }

            variableView {
                addTextView(etPhone)
                addTextView(etPassword)
                addOnValidationInterceptListener(::intercept)
                addOnValidationResultListener(buttonLogin)
            }
        }
    }

    private fun intercept(view: View): Boolean? = when (view) {
        vb.etPhone -> vb.etPhone.length() == 11
        vb.etPassword -> vb.etPassword.length() in 6..16
        else -> null
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.textLoginRegister -> launchStartActivityForResult(RegisterActivity::class.java) {
                goMain()
            }
            vb.textLoginForgetPassword -> startActivityExt<ForgetPasswordActivity>()
            vb.buttonLogin -> login()
        }
    }

    private fun login() {
        if (!vb.protocolView.isChecked()) {
            Utils.hideSoftInput(mThis)
            val animation = AnimationUtils.loadAnimation(this, R.anim.translate_checkbox_shake)
            vb.protocolView.startAnimation(animation)
            "请先同意协议".toastMessageLong()
            return
        }
        launchUILogin({ login(vb.etPhone.value, Md5Utils.getMD5(vb.etPassword.value)) },
            ApiObserver(this) {
                if (it != null) {
                    UserCache.saveToken(it.token)
                    UserCache.saveUserInfoBean(it)
                    goMain()
                }
            })
    }

    private fun goMain() {
        startActivityExt<MainActivity>()
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
        finish()
    }

}